package com.ruoyi.fts.wxconfig;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.fts.domain.FtsOrder;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import com.wechat.pay.java.service.refund.model.Status;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Component
public class WxJsapiService {
    public static String outTradeNoGen(){
        /****************订单号生成*******************/
        Long times=new Date().getTime();
        LocalDateTime now = LocalDateTime.now();
        // 创建一个DateTimeFormatter实例，指定日期和时间的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
        // 使用formatter格式化当前日期和时间
        String formattedDateTime = now.format(formatter);
        StringBuffer outTradeNoStr=new StringBuffer("wxRefund");
        outTradeNoStr.append(formattedDateTime);
        String timesStr=times.toString();
        String timesStr6=timesStr.substring(timesStr.length()-6,timesStr.length());
        outTradeNoStr.append(timesStr6);
        String outTradeNo=outTradeNoStr.toString();
        /***********************************/
        return outTradeNo;
    }

    /** 关闭订单 */
    public static boolean closeOrder(String OutTradeNo) {
        try{
            CloseOrderRequest request = new CloseOrderRequest();
            // 调用request.setXxx(val)设置所需参数，具体参数可见Request定义
            request.setMchid(WxPayInit.merchantId);
            request.setOutTradeNo(OutTradeNo);
            // 调用接口
            WxPayInit.service.closeOrder(request);
            return true;
        }catch (Exception e){
            return false;
        }

    }

    /**
     * 微信支付订单号查询订单
     * */
    public static Transaction queryOrderById(String transactionId) {

        QueryOrderByIdRequest request = new QueryOrderByIdRequest();
        // 调用request.setXxx(val)设置所需参数，具体参数可见Request定义
        request.setTransactionId(transactionId);
        request.setMchid(WxPayInit.merchantId);
        // 调用接口
        return WxPayInit.service.queryOrderById(request);
    }

    /**
     * 商户订单号查询订单
     * */
    public static Transaction queryOrderByOutTradeNo(String outTradeNo) {

        QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
        // 调用request.setXxx(val)设置所需参数，具体参数可见Request定义
        request.setOutTradeNo(outTradeNo);
        request.setMchid(WxPayInit.merchantId);
        // 调用接口
        return WxPayInit.service.queryOrderByOutTradeNo(request);
    }

    public static void refund(CreateRequest request){

        Refund  refund= WxPayInit.refundService.create(request);
        if(Status.SUCCESS==refund.getStatus()){
            //成功
        }
    }
}
